package cn.portx.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf3.dorado.jpa.JpaUtil;
import com.bstek.bdf3.security.orm.Role;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

import cn.portx.entity.ExpenseAuthority;
import cn.portx.entity.ExpenseItem;

@Component
public class ExpenseAuthorityPR {

	@DataProvider
	@Transactional(readOnly = true)
	public void loadRoles(Page<Role> page, Criteria criteria) {
		JpaUtil.linq(Role.class).where(criteria).paging(page);
	}

	@DataProvider
	@Transactional
	public List<ExpenseAuthority> loadExpenseAuthorities(Map<String, Object> params) {
		String roleId = (String) params.get("roleId");
		String type = (String) params.get("type");
		List<ExpenseItem> list = JpaUtil.linq(ExpenseItem.class).equal("type", type).notExists(ExpenseAuthority.class)
				.equalProperty("expenseItemId", "id").equal("roleId", roleId).end().list();
		List<ExpenseAuthority> authorities = new ArrayList<ExpenseAuthority>();
		for (ExpenseItem ei : list) {
			ExpenseAuthority ea = new ExpenseAuthority();
			ea.setId(UUID.randomUUID().toString());
			ea.setRoleId(roleId);
			ea.setExpenseItemId(ei.getId());
			ea.setAuthority("2");// 默认可看可改
			authorities.add(ea);
		}
		if (authorities.size() > 0) {
			JpaUtil.persist(authorities);
		}
		return JpaUtil.linq(ExpenseAuthority.class).collect(ExpenseItem.class, "expenseItemId").equal("roleId", roleId)
				.exists(ExpenseItem.class).equal("type", type).equalProperty("id", "expenseItemId").end().list();
	}

	@DataResolver
	@Transactional
	public void saveRole(Role role) {
		JpaUtil.save(role);
	}

	@Expose
	@Transactional
	public void deleteRole(String id) {
		JpaUtil.lind(Role.class).idEqual(id).delete();
	}

	@DataResolver
	@Transactional
	public void saveAuthority(List<ExpenseAuthority> receiveAuthorities, List<ExpenseAuthority> payAuthorities,
			List<ExpenseAuthority> costAuthorities) {
		if (receiveAuthorities != null && receiveAuthorities.size() > 0) {
			JpaUtil.save(receiveAuthorities);
		}
		if (payAuthorities != null && payAuthorities.size() > 0) {
			JpaUtil.save(payAuthorities);
		}
		if (costAuthorities != null && costAuthorities.size() > 0) {
			JpaUtil.save(costAuthorities);
		}
	}
}
